//
//  KKBarChartView.m
//  KKBarViewDemo
//
//  Created by liaozhenming on 16/3/26.
//  Copyright © 2016年 liaozhenming. All rights reserved.
//

#import "KKBarChartView.h"

@interface KKBarChartView() {
    
    UIView *_verticalView;
    NSMutableArray *_cellItems;
}

@end

@implementation KKBarChartView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame: frame];
    if (self) {
        [self private_initContentView];
    }
    return self;
}

- (instancetype)init {
    return [self initWithFrame: CGRectZero];
}

- (void)awakeFromNib {
    [self private_initContentView];
}

#pragma mark - Private methods

- (void)private_initContentView {
    
    _cellItems = [NSMutableArray array];
    
    _verticalView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 20, CGRectGetHeight(self.bounds))];
    [self addSubview: _verticalView];
    
    _kk_contentScrollView = [[UIScrollView alloc] initWithFrame: CGRectMake(20, 0, CGRectGetWidth(self.bounds) - 20, CGRectGetHeight(self.bounds))];
    [self addSubview: _kk_contentScrollView];
}

- (void)private_getMaxValueOfValues:(NSArray*)values maxValue:(double *)maxValue{
    
    if (![values isKindOfClass: [NSArray class]]) {
        return;
    }
    
    for (id obj in values) {
        if ([obj isKindOfClass: [NSArray class]]) {
            [self private_getMaxValueOfValues: obj maxValue: maxValue];
        }
        else if ([obj isKindOfClass: [NSNumber class]]) {
            
            double itemValue = [obj doubleValue];
            if (*maxValue < itemValue) {
                *maxValue = itemValue;
            }
        }
        else if ([obj isKindOfClass: [NSString class]]) {
            double itemValue = [obj doubleValue];
            if (*maxValue < itemValue) {
                *maxValue = itemValue;
            }
        }
    }
}

- (void)private_updateItemValueWithMaxValue:(double)maxValue maxHeight:(CGFloat)maxHeight itemValues:(NSArray*)values{
    
    id object = [values firstObject];
    [self private_updateItemValueWithMaxValue: maxValue maxHeight: maxHeight itemValues: values alone: [object isKindOfClass: [NSArray class]] ? YES : NO];
}

- (void)private_updateItemValueWithMaxValue:(double)maxValue maxHeight:(CGFloat)maxHeight itemValues:(NSArray*)values alone:(BOOL)alone {
    
    CGFloat offsetHeight = 10;
    CGFloat lateralItemOffsetWidth = 10;
    CGFloat lateralItemWidth = 20;
    
    if (!alone) {
        
        for (NSInteger index = 0; index < values.count; index++) {
            CGFloat pointX = index *(lateralItemWidth + lateralItemOffsetWidth);
            //  绘制横轴上的值
            double itemValue = [values[index] doubleValue];
            
            NSString *title = [NSString stringWithFormat: @"%.1f",itemValue];
            if ([self.dataSource respondsToSelector: @selector(chartView:cellTitleAtIndexPath:)]) {
                title = [self.dataSource chartView: self cellTitleAtIndexPath: [NSIndexPath indexPathForRow: index inSection: 0]];
            }
            
            float ratio = itemValue / maxValue;
            CGFloat itemViewHeight = ratio * maxHeight;
            KKBarChartViewCell *itemView = [[KKBarChartViewCell alloc] initWithFrame: CGRectMake(pointX, maxHeight - itemViewHeight + offsetHeight, lateralItemWidth-4, itemViewHeight) title: title];
            itemView.backgroundColor = [UIColor blueColor];
            [_kk_contentScrollView addSubview: itemView];
        }
    }
    else {
        for (NSInteger index = 0; index < values.count; index++) {
            
            NSArray *subValues = values[index];
            
            CGFloat pointX = index *(lateralItemWidth * subValues.count + lateralItemOffsetWidth);
            
            for (NSInteger subIndex = 0; subIndex < subValues.count; subIndex++) {
                
                CGFloat itemPointX = pointX + lateralItemWidth*subIndex;
                //  绘制横轴上的值
                double itemValue = [subValues[subIndex] doubleValue];
                
                NSString *title = [NSString stringWithFormat: @"%.1f",itemValue];
                if ([self.dataSource respondsToSelector: @selector(chartView:cellTitleAtIndexPath:)]) {
                    title = [self.dataSource chartView: self cellTitleAtIndexPath: [NSIndexPath indexPathForRow: subIndex inSection: index]];
                }
                
                float ratio = itemValue / maxValue;
                CGFloat itemViewHeight = ratio * maxHeight;
                KKBarChartViewCell *itemView = [[KKBarChartViewCell alloc] initWithFrame: CGRectMake(itemPointX, maxHeight - itemViewHeight + offsetHeight, lateralItemWidth-4, itemViewHeight) title: title];
                itemView.backgroundColor = [UIColor blueColor];
                [_kk_contentScrollView addSubview: itemView];
            }
        }
    }
}

#pragma mark - Public methods

- (void)reloadData {
    
    [_cellItems makeObjectsPerformSelector: @selector(removeFromSuperview)];
    [_verticalView.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];
    [_kk_contentScrollView.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];
    
    if (self.dataSource == nil || ![self.dataSource respondsToSelector:@selector(valuesOfLateralAxisInBarChartView:)]) {
        return;
    }
    
    NSArray *values = [self.dataSource valuesOfLateralAxisInBarChartView: self];
    
    if (values == 0) {
        return;
    }
    
    double verticalMaxValue;
    [self private_getMaxValueOfValues: values maxValue: &verticalMaxValue];
    
    NSLog(@"verticalMaxValue = %f", verticalMaxValue);
    if (verticalMaxValue == 0) {
        return;
    }
    
    NSInteger lateralItemCount = [values count];
    
    //  绘制纵轴的坐标系
    double contentHeight = CGRectGetHeight(_kk_contentScrollView.bounds);
    CGFloat offsetHeight = 10;
    contentHeight -= offsetHeight * 2;    // 上下各10像素的空间
    {
        double verticalOffsetValue = verticalMaxValue / 10.0;
        
        double verticalOffsetHeight = contentHeight / 10.0;
        for (NSInteger index = 0; index < 11; index++) {
            
            UILabel *verticalTitleLabel = [[UILabel alloc] initWithFrame: CGRectMake(0, contentHeight - verticalOffsetHeight * index - 5 + offsetHeight, 20, 10)];
            verticalTitleLabel.backgroundColor = [UIColor clearColor];
            verticalTitleLabel.textAlignment = NSTextAlignmentRight;
            verticalTitleLabel.font = [UIFont systemFontOfSize: 8];
            verticalTitleLabel.textColor = [UIColor purpleColor];
            verticalTitleLabel.text = [NSString stringWithFormat: @"%.0f-",floor(verticalOffsetValue * index)];
            [_verticalView addSubview: verticalTitleLabel];
        }
        
        UIView *verticalLineView = [[UIView alloc] initWithFrame: CGRectMake(20, 0, 1, contentHeight + offsetHeight)];
        verticalLineView.backgroundColor = [UIColor purpleColor];
        [_verticalView addSubview: verticalLineView];
    }
    
    //  绘制横轴的坐标及其数据
    {
        
        CGFloat lateralItemOffsetWidth = 10;
        CGFloat lateralItemWidth = 20;
        
        id itemValue = [values firstObject];
        if ([itemValue isKindOfClass: [NSArray class]]) {
            lateralItemWidth = lateralItemWidth * [(NSArray*)itemValue count];
        }
        
        for (NSInteger index = 0; index < lateralItemCount; index++) {
            
            CGFloat pointX = index *(lateralItemWidth + lateralItemOffsetWidth);
            
            NSString *title = [NSString stringWithFormat: @"%@",@(index)];
            if ([self.dataSource respondsToSelector: @selector(chartView:lateralAxisTitleAtIndex:)]) {
                title = [self.dataSource chartView: self lateralAxisTitleAtIndex: index];
            }
            
            UILabel *lateralTitleLabel = [[UILabel alloc] initWithFrame: CGRectMake(pointX, contentHeight + offsetHeight, lateralItemWidth, 10)];
            lateralTitleLabel.backgroundColor = [UIColor clearColor];
            lateralTitleLabel.textAlignment = NSTextAlignmentCenter;
            lateralTitleLabel.font = [UIFont systemFontOfSize: 8];
            lateralTitleLabel.textColor = [UIColor purpleColor];
            lateralTitleLabel.text = title;
            [_kk_contentScrollView addSubview: lateralTitleLabel];
        }
        UIView *lateralLineView = [[UIView alloc] initWithFrame: CGRectMake(0, contentHeight + offsetHeight, lateralItemCount * (lateralItemWidth + lateralItemOffsetWidth), 1)];
        lateralLineView.backgroundColor = [UIColor purpleColor];
        [_kk_contentScrollView addSubview: lateralLineView];
        _kk_contentScrollView.contentSize = CGSizeMake(lateralItemCount * (lateralItemWidth + lateralItemOffsetWidth), 0);
    }
    
    //  绘制横轴上的值
    {
        [self private_updateItemValueWithMaxValue: verticalMaxValue maxHeight: contentHeight itemValues: values];
    }
}


@end

@implementation KKBarChartViewCell

- (instancetype)initWithFrame:(CGRect)frame title:(NSString *)title {
    self = [super initWithFrame: frame];
    if (self) {
        
        self.clipsToBounds = NO;
        if (title.length > 0) {
            UILabel *titleLabel = [[UILabel alloc] initWithFrame: CGRectMake(-5, -9, CGRectGetWidth(frame) + 10, 10)];
            titleLabel.backgroundColor = [UIColor clearColor];
            titleLabel.textColor = [UIColor redColor];
            titleLabel.font = [UIFont systemFontOfSize: 8];
            titleLabel.textAlignment = NSTextAlignmentCenter;
            titleLabel.text = title;
            [self addSubview: titleLabel];
        }
    }
    return self;
}

@end
